package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;

public class Biblioteca {
    String welcomeMessage;
    PrintStream printStream;
    BufferedReader bufferedReader;
    private CheckoutBookCommand checkoutCommand;
    List<LibraryBook> bookList;
    Map<String, String> options;
    private ListBookCommand listBookCommand;

    public Biblioteca(PrintStream printStream, String welcomeMessage, List<LibraryBook> bookList, Map<String, String> options,
                      BufferedReader bufferedReader, CheckoutBookCommand checkoutCommand, ListBookCommand listBookCommand) {
        this.welcomeMessage = welcomeMessage;
        this.printStream = printStream;
        this.bookList = bookList;
        this.options = options;
        this.bufferedReader = bufferedReader;
        this.checkoutCommand = checkoutCommand;
        this.listBookCommand = listBookCommand;
    }

    public void run(){
        displayWelcomeMessage();
        listBookCommand.listBooks();
        try {
            String choice = menu(options, printStream);
            executeUserChoice(choice);
        } catch (IOException e) {
            printStream.println("Error Reading Input");
        }
    }

    public void displayWelcomeMessage() {
        printStream.println(welcomeMessage);
    }


    public void displayOptions() {
        for(String option : options.values())
            printStream.println(option);
    }

    public void executeUserChoice(String userChoice) throws IOException {
        if(userChoice.equals("1")){
            listBookCommand.listBooks();
        }
        else if(userChoice.equals("2")){
            checkoutCommand.checkoutBook();
        }
    }



    public String menu(Map options, PrintStream printStream) throws IOException {
        String choice ="";
        boolean isInvalidOption = true;
        while(isInvalidOption){
            displayOptions();
            choice = getUserOptionChoice();

            if(options.containsKey(choice)){
                isInvalidOption = false;
            }
            else
                printStream.println("Select a valid option!");
        }
        return choice;
    }

    public String getUserOptionChoice() throws IOException {
        return bufferedReader.readLine();
    }

}
